<template lang="pug">
  .page
    .AccountsReceivableManage
      .search-form.mb-10.pl-10.pr-10
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="90")
          FormItem.form-item.ivu-col.pr-20.mb-15(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder")
            template(v-if="item.type === 'interval'")
              DatePicker.pull-left.interval(v-model="formData[item.model1]" :value="datePickerDefault" :placeholder="item.placeholder1" type="month" @on-change="handleChangeDatePicker")
              span.pl-10.pr-10.pull-left.line-h-32 --
              DatePicker.pull-left.interval(v-model="formData[item.model2]" :value="datePickerDefault" :placeholder="item.placeholder2" type="month" @on-change="handleChangeDatePicker")
            template(v-if="item.type === 'button'")
              Button(type="info" @click="searchFn") 查询

      .pl-20.pr-20.bg-white
        Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          .clearfix.pr-24.pl-12.overflow-hidden(slot="header")
            .table-title-lefttxt.pull-left
              |合计：
              span.text-info.pl-5.pr-5.font-weight {{tableComone.totalRows}}
              |条
              Divider(type="vertical")
              |工资应付：
              span.text-info.pl-5.pr-5.font-weight {{tableComone.salaryTotal}}
              |元
              Divider(type="vertical")
              |个税应付：
              span.text-info.pl-5.pr-5.font-weight {{tableComone.incomeTotal}}
              |元
            .pull-right.table-title-btns
              Button.mr-10(type="info" v-if="hasToConfirmPay" @click="handleShowPayTaxModal" :disabled="$moment(formData.feeDateStart).format('YYYY-MM') != $moment(formData.feeDateEnd).format('YYYY-MM')") 个税付款确认
              Button.mr-10(type="info" v-if="hasExport" @click="handleExport") 导出
              Button(v-if="hasExportPaymentU8" type="info" @click="exportPayment") 导出实付单-U8
          .clearfix.pl-20.pr-20(slot="footer")
            Page(
              :total="tableComone.totalRows"
              @on-change="onChangePage"
              @on-page-size-change="onpageSizeChange"
              show-sizer
              show-total
              placement="top"
              prev-text="上一页"
              next-text="下一页"
              :page-size-opts="[10, 20, 30, 50, 100]"
            )
          template(slot-scope="{ row, index }" slot="action")
            Button.mr-10(type="text" v-if="hasGetList" @click="goDetail(row.customerGUID, row.customerName, row.salaryMonth)") 明细
            Button(type="text" v-if="hasConfirmPay" @click="handleShowPayModal(row)") 确认付款
    //- 付款弹窗
    PayModal(ref="PayModal" @query="searchFn")
    //- 个税付款弹窗
    PayTaxModal(ref="PayTaxModal" @query="searchFn")
</template>

<script>
import { SalaryPayableBillApi } from "@/api/SalaryPayableBill.api.js"
import { SalaryThead } from "./tableHead.js"
import _cloneDeep from "clone-deep"
import { EmployeesApi } from "@/api/Employees.api.js"
import PayModal from "../publicModal/payModal.vue"
import PayTaxModal from "../publicModal/payTaxModal.vue"
// import expandRow from './table-expand.vue'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: "",

  components: {
    // expandRow
    PayModal,
    PayTaxModal
  },

  data() {
    return {
      companyId: "", // 公司ID
      companyName: "", // 公司名称
      employeeId: "", // 员工ID
      thead: _cloneDeep(SalaryThead),
      tableData: [],
      formData: {
        companyName: "",
        feeDateStart: new Date(),
        feeDateEnd: new Date()
      },
      formItem: [
        { type: "input", label: "客户名称：", placeholder: "请输入客户名称", prop: "companyName", model: "companyName", style: "ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6" },
        { type: "interval", label: "费用月份：", placeholder1: "开始日期", prop1: "feeDateStart", model1: "feeDateStart", placeholder2: "结束日期", prop2: "feeDateEnd", model2: "feeDateEnd", style: "ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6" },
        { type: "button", style: "ivu-col-span-md-24 ivu-col-span-lg-12 ivu-col-span-xl-8 ivu-col-span-xxl-6" }
      ],
      rules: {},
      selectedEmployeeId: [], // 勾选的id集合,array格式
      selectedEmployeeArr: [], // 勾选的id, name数组集合
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        total: 0, // 合计
        salaryTotal: 0,
        incomeTotal: 0,
      },
      downLoadRul: "",
      arrListDown: {
        bankList: []
      },
      datePickerDefault: new Date(), // 当前时间
    };
  },

  watch: {},

  computed: {
    actionArr() {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code;
      });
      return arr;
    },
    // 导出
    hasExport() {
      return this.actionArr.indexOf("Export") > -1;
    },
    // 导出实付单-U8
    hasExportPaymentU8 () {
      return this.actionArr.indexOf('ExportPaymentU8') > -1
    },
    // 查询
    hasFind() {
      return this.actionArr.indexOf("Find") > -1;
    },
    // 明细
    hasGetList() {
      return this.actionArr.indexOf("GetList") > -1;
    },
    // 工资确认付款
    hasConfirmPay() {
      return this.actionArr.indexOf("ConfirmPay") > -1;
    },
    // 个税确认付款
    hasToConfirmPay() {
      return this.actionArr.indexOf("ToConfirmPay") > -1;
    }
  },

  
  mounted() {
    this.query()
  },

  methods: {
    // 搜索
    searchFn() {
      this.tableComone.pageIndex = 1;
      this.query();
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage(val) {
      this.tableComone.pageIndex = val;
      this.query();
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange(val) {
      this.tableComone.pageIndex = 1;
      this.tableComone.pageSize = val;
      this.query();
    },
    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query() {
      var params = {
        HasPaging: true,
        CompanyName: this.formData.companyName,
        FeeDateStart: this.formData.feeDateStart,
        FeeDateEnd: this.formData.feeDateEnd,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      };
      let res = await SalaryPayableBillApi.getList(
        params
      );
      console.log("应付res: ", res);
      if (res.status === 200 && res.data.success) {
        this.tableData = res.data.data;
        this.tableComone.totalRows = res.data.totalRows;
        this.tableComone.total = res.data.total;
        this.tableComone.salaryTotal = res.data.salaryTotal;
        this.tableComone.incomeTotal = res.data.incomeTotal;
      } else {
        this.tableData = [];
      }
      this.loading = false;
    },

    // 表格选择操作
    handleOnSelectChange(value) {
      this.selectedEmployeeArr = value.map(item => {
        return { id: item.id, name: item.name };
      });
      this.selectedEmployeeId = value.map(item => {
        return item.id;
      });
      console.log("列表勾选数组1", this.selectedEmployeeArr);
      console.log("列表勾选数组2", this.selectedEmployeeId);
    },

    // 日期选择
    handleChangeDatePicker(val) {
      console.log("val: ", val);
      // this.formData.salaryMonth = val
      // this.getDayList()
    },

    // 导出薪资应付账单
    async handleExport() {
      var params = {
        HasPaging: true,
        CompanyName: this.formData.companyName,
        FeeDateStart: this.formData.feeDateStart,
        FeeDateEnd: this.formData.feeDateEnd,
        PageIndex: this.tableComone.pageIndex,
        PageSize: this.tableComone.pageSize
      };
      console.log("params: ", params);
      let res = await SalaryPayableBillApi.export(
        params
      );
      console.log("导出薪资应付账单res: ", res);
      if (res.status === 200 && res.data.success) {
        console.log("返回链接: ", res.data.message);
        window.open(baseUrl + res.data.message, "_blank");
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        });
      }
    },

    // 导出实付单-U8
    async exportPayment () {
      let res = await SalaryPayableBillApi.exportPayment()
      console.log('导出实付单-U8 res: ', res)
      if (res.status === 200 && res.data.success) {
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 付款-显示弹窗
    handleShowPayModal (row) {
      this.$refs.PayModal.getBankList()
      // this.$refs.PayModal.show()
      this.$refs.PayModal.modalType = 'salary'
      this.$refs.PayModal.formData.amount = row.salaryPayable
      Object.keys(this.$refs.PayModal.salaryParams).forEach(key => {
        this.$refs.PayModal.salaryParams[key] = row[key]
      })
      this.$refs.PayModal.checkConfirmPay()
    },

    // 个税付款-显示弹窗
    handleShowPayTaxModal () {
      this.$refs.PayTaxModal.getBankList()
      Object.keys(this.$refs.PayTaxModal.defaultParamsData).forEach(key => {
        this.$refs.PayTaxModal.defaultParamsData[key] = this.formData[key]
      })
      this.$refs.PayTaxModal.checkConfirmPay()
    },

    // 去详情
    goDetail (companyId, companyName, feeDate) {
      this.$router.push({
        path: '/salaryPayableDetail',
        name: 'salaryPayableDetail',
        query: {
          companyId: companyId,
          companyName: companyName,
          feeDate: feeDate,
        }
      })
    }
  } // methods end
}
</script>

<style lang="less" scoped>
</style>
